<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/29 0029
 * Time: 9:57
 */

function noncestr($data){//获取随机数
    if(cookie('noncestr')){
        return cookie('noncestr');
    }else{
        $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
        $password='';
        for($i=0;$i<=$data;$i++){
            $password.=substr($chars, mt_rand(0, strlen($chars)-1),1);
        }
        cookie('noncestr',$password,7200);
        return $password;
    }
}
function getAppid(){
    $typeName=cookie('getTokenType');
    if($typeName){
        $appidArr=M()->query("select * from gzh_appid_appsecret where typeName='{$typeName}'");
        //dump($appidArr);
    }

    cookie('wxKEY',C('KEY'));
    if($appidArr[0]['APPID']){
        cookie('APPID',$appidArr[0]['APPID']);
        cookie('APPSECRET',$appidArr[0]['APPSECRET']);
        cookie('MCHID',$appidArr[0]['MCHID']);
    }else{//支付公众号切换位置
        cookie('APPID',C("APPID"));//知命
        cookie('APPSECRET',C("APPSECRET"));
        cookie('MCHID',C('GMCHID'));
//        cookie('APPID',C("H5APPID"));//趣味测试
//        cookie('APPSECRET',C("H5APPSECRET"));
//        cookie('MCHID',C('H5GMCHID'));
    }

    if($_SERVER['HTTP_HOST']=='xinbang.pingushi.cn'){
        cookie('APPID',C("H5APPID"));//趣味测试
        cookie('APPSECRET',C("H5APPSECRET"));
        cookie('MCHID',C('H5GMCHID'));
    }elseif($_SERVER['HTTP_HOST']=='wx.xbd61.net.cn'){
        cookie('http','http',36000);
        cookie('APPID',C("XzAPPID"));
        cookie('APPSECRET',C("XzAPPSECRET"));
        cookie('MCHID',C('XzGMCHID'));
        cookie('wxKEY',C('XzKey'));
    }
}

//拿到access_token
function getToken(){
    getAppid();
    $id = cookie('APPID');
    $secret = cookie('APPSECRET');
    $accessTokenArr=M()->query("select * from gzh_access_token where appid='{$id}'");
    $nowTime=time();
    $oldTime=$accessTokenArr[0]['createtime'];
    if($nowTime-$oldTime>=6000){
        S('token'.$id,null);
        S('ticket'.$id,null);
    }else{
        if(S('token'.$id)!=''){
            S('token'.$id,$accessTokenArr[0]['access_token'],7000-($nowTime-$oldTime));
        }
    }
    if($_SERVER['HTTP_HOST']=='wx1.bazijingpi.top'){//支付域名执行
        return 1;
    }

    if(S('token'.$id)!=''){
        return S('token'.$id);
    }else {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$id}&secret={$secret}";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);//设置请求地址
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//不需要证书验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//不需要主机验证
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $json = curl_exec($ch);
        $arr = json_decode($json, true);
        M()->query("update gzh_access_token set access_token='{$arr['access_token']}',createtime='{$nowTime}' where appid='{$id}'");
        S('token'.$id,$arr['access_token'],7100);
        S('token',$arr['access_token'],7100);
        return $arr['access_token'];
        curl_close($ch);
    }
}

//拿到jsapi_ticket
function getTicket(){
    if($_SERVER['HTTP_HOST']=='wx1.bazijingpi.top'){//支付域名执行
        return 1;
    }

    $id = cookie('APPID');
    if(S('ticket'.$id)!=''){
        return S('ticket'.$id);
    }else{
        $token = S('token'.$id);
        $url ="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$token}&type=jsapi";
        $ch=curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);//设置请求地址
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不需要证书验证
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);//不需要主机验证
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        $json = curl_exec($ch);
        $arr=json_decode($json,true);
        if($arr['errcode']=='40001'){//过期重新获取
            overdueGet();
        }
        S("ticket".$id,$arr['ticket'],7100);
        S("ticket",$arr['ticket'],7100);
        return $arr['ticket'] ;
        curl_close($ch);
    }
}
function overdueGet(){//过期重新获取
//    $id = cookie('APPID');
//    $secret = cookie('APPSECRET');
//    $nowTime=time();
//    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$id}&secret={$secret}";
//    $json = curlGet($url);
//    $arr = json_decode($json, true);
//    M()->query("update gzh_access_token set access_token='{$arr['access_token']}',createtime='{$nowTime}' where appid='{$id}'");
//    S('token'.$id,$arr['access_token'],7100);

}
function getCode($url){ //获取code
    if($_SERVER['HTTP_HOST']=='wx1.bazijingpi.top'){//支付域名执行
        return 1;
    }

    if(cookie('code')!=''){
        return cookie('code');
    }else{
        $APPID = cookie('APPID');
        $url=urlencode($url);
        $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid={$APPID}&redirect_uri={$url}&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
        redirect($url);
    }
}

function getOopenid(){ //获取openid
    if($_SERVER['HTTP_HOST']=='wx1.bazijingpi.top'){//支付域名执行
        return 1;
    }

    if(cookie('openid')){
        return cookie('openid');
    }else {
        $APPID = cookie('APPID');
        $APPSECRET = cookie('APPSECRET');
        $code = cookie('code');
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$APPID}&secret={$APPSECRET}&code={$code}&grant_type=authorization_code";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);//设置请求地址
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//不需要证书验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//不需要主机验证
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $json = curl_exec($ch);
        $arr = json_decode($json, true);
        if($arr['openid']){
            cookie("openid",$arr['openid']);
        }else{//获取失败
            M()->query("update gzh_access_token set createtime='1' where appid='{$APPID}'");
            cookie('code',null);
            dump($arr);
            sleep(1);
            redirect(cookie('wzurl'));
            return 0;
        }
        return $arr['openid'];
    }
}
function getUsertext(){  //获取微信用户的信息
    $token = S('token');
    $openid=cookie('openid');
    $url ="https://api.weixin.qq.com/cgi-bin/user/info?access_token={$token}&openid={$openid}";
    $ch=curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);//设置请求地址
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不需要证书验证
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);//不需要主机验证
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    $json = curl_exec($ch);
    $arr=json_decode($json,true);
    cookie("zusertext",$arr);
    return $arr;
}

function wxGetCode($url){ //授权获取code
    if(cookie('code')!=''){
        return cookie('code');
    }else{
        $APPID = C("APPID");
        $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid={$APPID}&redirect_uri={$url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        redirect($url);
    }
}
function Caccess_token(){//使用code换取access_token
    if(cookie("openid")&&cookie('accessToken')){

    }else{
        $APPID = C("APPID");
        $secret = C("APPSECRET");
        $code = cookie('code');
        $url ="https://api.weixin.qq.com/sns/oauth2/access_token?appid={$APPID}&secret={$secret}&code={$code}&grant_type=authorization_code";
        $ch=curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);//设置请求地址
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不需要证书验证
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);//不需要主机验证
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        $json = curl_exec($ch);
        $arr=json_decode($json,true);
        if($arr['openid']){
            cookie('accessToken',$arr['access_token'],7100);
            cookie("openid",$arr['openid']);
        }
    }
}
function wxgetUsertext(){  //授权获取微信用户的信息
    $accessToken=cookie('accessToken');
    $openid=cookie('openid');
    $url ="https://api.weixin.qq.com/sns/userinfo?access_token={$accessToken}&openid={$openid}&lang=zh_CN";
    $ch=curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);//设置请求地址
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不需要证书验证
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);//不需要主机验证
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    $json = curl_exec($ch);
    $arr=json_decode($json,true);
    return $arr;
}

function cnzz_pvuv($name){//pV uV  统计
    $baseNum=dataBaseNum();
    if(empty($baseNum)){//终止执行
        return $baseNum;
    }
    $date=date('Ymd');
    $channel=cookie('channel');
    if(strlen($channel)>50){exit;}


    $pvNumber=S('pv'.$date.$channel.$name);
    if(empty($pvNumber)){
        S('pv'.$date.$channel.$name,1,86400);
        S('uv'.$date.$channel.$name,1,86400);
    }else{
        S('pv'.$date.$channel.$name,$pvNumber+1,86400);
    }

    $pvNumber=S('pv'.$date.$channel.$name);
    $uvNumber=S('uv'.$date.$channel.$name);
    $cnzzPvuvNum=S('cnzzDown'.$date.$channel.$name);

    //UV
    $UvName=$channel.$name;
    $ip=$_SERVER['REMOTE_ADDR'];
    $timex=time();
    $timey=strtotime("+1 day",strtotime($date));
    $timedata=$timey-$timex;
    $UvNameData=cookie($UvName);

    if(empty($UvNameData)){
        S('uv'.$date.$channel.$name,$uvNumber+1,86400);
        cookie($UvName,1,$timedata);
    }

    cnzz_pvuv_timeSlot($channel,$name,$UvNameData);//分时间段统计
    childPvuv($name);//子渠道统计

    if($cnzzPvuvNum==''){
        //PV
        S('cnzzDown'.$date.$channel.$name,1,300);
        $cnzzArr=M()->query("select id,pv,zpv,uv,zuv from tb_cnzz_pvuv where date='{$date}' and channel='{$channel}' and csName='{$name}' limit 1");

        if(empty($cnzzArr)){
            M()->query("insert into tb_cnzz_pvuv (date,channel,csName,pv,uv,zpv,zuv)values(
                    '{$date}','{$channel}','{$name}',1,1,1,1)");
        }else{
            if($cnzzArr[0]['pv']>$pvNumber){
                S('pv'.$date.$channel.$name,$cnzzArr[0]['pv'],86400);
                S('uv'.$date.$channel.$name,$cnzzArr[0]['uv'],86400);
                $pvNumber=S('pv'.$date.$channel.$name);
                $uvNumber=S('uv'.$date.$channel.$name);
            }
            M()->query("update tb_cnzz_pvuv set pv='{$pvNumber}',zpv='{$pvNumber}' where id='{$cnzzArr[0]['id']}'");
        }

        //UV
        if($uvNumber>=1){
            M()->query("update tb_cnzz_pvuv set uv='{$uvNumber}',zuv='{$uvNumber}' where id='{$cnzzArr[0]['id']}'");
        }

    }else{
        return '1';
    }

    //公共页点击统计
    $zmClickArr=M()->query("select type,number from tb_cnzz_index where nickname='zhiming'");
    foreach($zmClickArr as $key=>$value){
        cookie($value['type'].'Number',$value['number']);
    }


    //对昨天收入重新统计
    if(S('yesterdayS'.$name.$channel)==''){
        S('yesterdayS'.$name.$channel,1,$timedata);
        $typeArr=M()->query("select id from sm_h5test_type where shortname='{$name}'");
        $csTypeid=$typeArr[0]['id'];
        $csName=$name;
        //总价格统计入库
        $timey=strtotime("-1 day",strtotime($date));
        $date=date('Ymd',$timey);
        $yesterdayCX=date('Y-m-d 00:00:00',$timey);
        $yesterdayCXlt=date('Y-m-d 23:59:59',$timey);
        $cnzzArr=M()->query("select id,yesterday_select from tb_cnzz_pvuv where date='{$date}' and channel='{$channel}' and csName='{$csName}' limit 1");

        if($cnzzArr[0]['yesterday_select']<=1){
            $totalPrice=M()->query("select sum(price) price,count(id) id from sm_h5test where createtime >='{$yesterdayCX}' and createtime <='{$yesterdayCXlt}' and typeid='{$csTypeid}' and channel='{$channel}' and status=1");
            if($totalPrice[0]['price']){
                M()->query("update tb_cnzz_pvuv set totalPrice='{$totalPrice[0]['price']}',transactionNum='{$totalPrice[0]['id']}',yesterday_select=2 where id='{$cnzzArr[0]['id']}'");
            }
        }
    }
}
function childPvuv($name){//子渠道pvuv统计

    $child=cookie('child');
    $date=date('Ymd');
    $childName="C_{$child}";
    if(strlen($childName)>50){exit;}


    $pvNumber=S('pv'.$date.$childName.$name);
    if(empty($pvNumber)){
        S('pv'.$date.$childName.$name,1,86400);
        S('uv'.$date.$childName.$name,1,86400);
    }else{
        S('pv'.$date.$childName.$name,$pvNumber+1,86400);
    }

    $pvNumber=S('pv'.$date.$childName.$name);
    $uvNumber=S('uv'.$date.$childName.$name);
    $cnzzPvuvNum=S('cnzzDown'.$date.$childName.$name);

//UV
    $UvName=$childName.$name;
    $timex=time();
    $timey=strtotime("+1 day",strtotime($date));
    $timedata=$timey-$timex;
    $UvNameData=cookie($UvName);

    if(empty($UvNameData)){
        S('uv'.$date.$childName.$name,$uvNumber+1,86400);
        cookie($UvName,1,$timedata);
    }

    cnzz_pvuv_timeSlot($childName,$name,$UvNameData);//分时间段统计

    if($cnzzPvuvNum==''){
//PV
        S('cnzzDown'.$date.$childName.$name,1,300);
        $cnzzArr=M()->query("select id,pv,zpv,uv,zuv from tb_cnzz_pvuv where date='{$date}' and channel='{$childName}' and csName='{$name}' limit 1");

        if(empty($cnzzArr)){
            M()->query("insert into tb_cnzz_pvuv (date,channel,csName,pv,uv,zpv,zuv)values(
'{$date}','{$childName}','{$name}',1,1,1,1)");
        }else{
            if($cnzzArr[0]['pv']>$pvNumber){
                S('pv'.$date.$childName.$name,$cnzzArr[0]['pv'],86400);
                S('uv'.$date.$childName.$name,$cnzzArr[0]['uv'],86400);
                $pvNumber=S('pv'.$date.$childName.$name);
                $uvNumber=S('uv'.$date.$childName.$name);
            }
            M()->query("update tb_cnzz_pvuv set pv='{$pvNumber}',zpv='{$pvNumber}' where id='{$cnzzArr[0]['id']}'");
        }

//UV
        if($uvNumber>=1){
            M()->query("update tb_cnzz_pvuv set uv='{$uvNumber}',zuv='{$uvNumber}' where id='{$cnzzArr[0]['id']}'");
        }

    }else{
        return '1';
    }
}
function cnzz_pvuv_timeSlot($channel,$name,$UvNameData){//分时间段统计
    if($channel=='qudao294'||$channel=='qudao138'){
        $date=date('YmdH');
        $pvNumber=S('pv'.$date.$channel.$name);
        if(empty($pvNumber)){
            S('pv'.$date.$channel.$name,1,3600);
            S('uv'.$date.$channel.$name,1,3600);
        }else{
            S('pv'.$date.$channel.$name,$pvNumber+1,3600);
        }

        $pvNumber=S('pv'.$date.$channel.$name);
        $uvNumber=S('uv'.$date.$channel.$name);
        $cnzzPvuvNum=S('cnzzDown'.$date.$channel.$name);

        //UV
        $UvName=$channel.$name;
        $timex=time();
        $timey=strtotime("+1 day",strtotime($date));
        $timedata=$timey-$timex;

        if(empty($UvNameData)){
            S('uv'.$date.$channel.$name,$uvNumber+1,3600);
            cookie($UvName,1,$timedata);
        }

        if($cnzzPvuvNum==''){
            //PV
            S('cnzzDown'.$date.$channel.$name,1,300);
            $cnzzArr=M()->query("select id,pv,uv from tb_cnzz_pvuv_time_slot where date='{$date}' and channel='{$channel}' and csName='{$name}' limit 1");
            if(empty($cnzzArr)){
                M()->query("insert into tb_cnzz_pvuv_time_slot (date,channel,csName,pv,uv)values(
                    '{$date}','{$channel}','{$name}',1,1)");
            }else{
                if($cnzzArr[0]['pv']>$pvNumber){
                    S('pv'.$date.$channel.$name,$cnzzArr[0]['pv'],3600);
                    S('uv'.$date.$channel.$name,$cnzzArr[0]['uv'],3600);
                    $pvNumber=S('pv'.$date.$channel.$name);
                    $uvNumber=S('uv'.$date.$channel.$name);
                }
                M()->query("update tb_cnzz_pvuv_time_slot set pv='{$pvNumber}' where id='{$cnzzArr[0]['id']}'");
            }
            //UV
            if($uvNumber>=1){
                M()->query("update tb_cnzz_pvuv_time_slot set uv='{$uvNumber}' where id='{$cnzzArr[0]['id']}'");
            }
        }
    }
}
function wxOrderPayjudge($orderid){//微信支付订单判断
    $str6=substr($orderid,0,6);
    if($str6=='BZJPPT'){
        return 1;
    }

    $arrdata=S('sm_h5test|'.$orderid);
    if($arrdata['price']>0&&$arrdata['ordernum']){

    }else{
        header('location:'.U('Index/mycesuan','',false));
        exit;
    }
}
function wxgzhzf($nick,$name,$orderid){//微信公众号支付
    getOopenid();

    $price=cookie('price');
    if(empty($nick)){echo 'nike';exit;}

    $Unifiedorder=S('wxgzhzfUnifiedorder'.$orderid);
    $xmlstring = simplexml_load_string($Unifiedorder, 'SimpleXMLElement', LIBXML_NOCDATA);
    $valXml = json_decode(json_encode($xmlstring),true);


    if($Unifiedorder&&$valXml['result_code']!='FAIL'){
    }else{
        $arrdata[0]=S('sm_h5test|'.$orderid);
        if($arrdata[0]['price']>0&&$arrdata[0]['status']!=1){
            if(cookie('wxzfNum')){
                cacheZhiFuOrderidDelete($orderid);//删除用户我的测试订单
                $orderid=$nick.date('Ymd').mt_rand(1000,9999).date('His');//重新生成订单
                cookie('orderid',$orderid);
                $arrdata[0]['ordernum']=$orderid;
                S('sm_h5test|'.$orderid,$arrdata[0],2592000);//2592000为30天
                cacheZhiFuOrderid($orderid);//支付页缓存订单操作
                //M()->query("insert into sm_h5test(ordernum,price,username,typeid,sex,status,datetype,year,month,day,hour,minute,channel,ip,appuserid,auto_send_sms) select '{$orderid}' as ordernum,price,username,typeid,sex,status,datetype,year,month,day,hour,minute,channel,ip,appuserid,auto_send_sms from sm_h5test where id='{$arrdata[0]['id']}'");
                if($nick=='HH'||$nick=='HY'){
                    //M()->query("insert into sm_h5test(ordernum,price,username,typeid,sex,status,datetype,year,month,day,hour,channel,ip,appuserid) select '{$orderid}_' as ordernum,price,username,typeid,sex,status,datetype,year,month,day,hour,channel,ip,appuserid from sm_h5test where id={$arrdata[0]['id']}+1");
                }
            }
            cookie('wxzfNum',1);
        }else{
            header('location:'.U('Index/mycesuan','',false));
            exit;
        }
    }


    wxOrderPayjudge($orderid);//微信支付订单判断

    if(empty($price)){$price=28;}
    $price*=100;

    $noncestr=noncestr(15);
    $APPID = cookie('APPID');
    $MCHID=cookie('MCHID');
    $wxKey=cookie('wxKEY');

    //重新定义商品名称
    $name="订单号:{$orderid},客服微信号:qumingxiaoxue";

    $body=$name;
    $notifyUrl="http://{$_SERVER['HTTP_HOST']}/zhiming/index.php/Home-Index-notify_urlwx";
    $stringA="appid=".$APPID."&body={$body}&mch_id={$MCHID}&nonce_str={$noncestr}&notify_url={$notifyUrl}&openid=".cookie("openid")."&out_trade_no={$orderid}&spbill_create_ip={$_SERVER['REMOTE_ADDR']}&total_fee={$price}&trade_type=JSAPI";
    $stringSignTemp=$stringA."&key=".$wxKey; //注：key为商户平台设置的密钥key
    $sign=strtoupper(md5($stringSignTemp));

    $strData=array(
        'appid'=>$APPID,
        'mch_id'=>$MCHID,
        'nonce_str'=>$noncestr,
        'sign'=>$sign,
        'body'=>$body,
        'out_trade_no'=>$orderid,
        'total_fee'=>$price,
        'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'],
        'notify_url'=>$notifyUrl,
        'trade_type'=>'JSAPI',
        'openid'=>cookie("openid"),
    );

    $xml = "<xml>";
    foreach ($strData as $key=>$val)//数组转xml
    {
        if (is_numeric($val)){
            $xml.="<".$key.">".$val."</".$key.">";
        }else{
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
    }
    $xml.="</xml>";
    $strData=$xml;
    //$json=json_encode($data,JSON_UNESCAPED_UNICODE);
    $headers=array(
        'Content-Type:text/xml;charset=utf-8',
    );
    $url="https://api.mch.weixin.qq.com/pay/unifiedorder";


    if($Unifiedorder&&$valXml['result_code']!='FAIL'){
        $json=$Unifiedorder;
    }else{
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
        curl_setopt($ch,CURLOPT_URL,$url); //设置请求地址
        curl_setopt($ch,CURLOPT_POST,true); //post请求
        curl_setopt($ch,CURLOPT_POSTFIELDS,$strData);// post请求的数据
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不需要证书验证
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//不直接输出到页面
        $json = curl_exec($ch);
        S('wxgzhzfUnifiedorder'.$orderid,$json,7200);
    }

    //错误提示
    $xmlstring = simplexml_load_string($json, 'SimpleXMLElement', LIBXML_NOCDATA);

    if($_SERVER['HTTP_HOST']=='xinbang.pingushi.cn'){
       dump($xmlstring);
    }
    $val = json_decode(json_encode($xmlstring),true);
    if(empty($val['prepay_id'])){
        dump($val);
        echo 'wxgzhzf';exit;
    }

    return $json;
    curl_close($ch);
}
function wxgzhzfInterface($name,$orderid,$notifyUrl=null){//微信公众号支付接口
    getAppid();
    $APPID=cookie('APPID');
    $price=cookie('price');
    $price*=100;

    $noncestr=noncestr(15);
    $MCHID=cookie('MCHID');
    $body=$name;
    if(empty($notifyUrl)){
        $notifyUrl="http://{$_SERVER['HTTP_HOST']}/zhiming/index.php/Home-Index-notify_urlwx";
    }
    $stringA="appid={$APPID}&body={$body}&mch_id={$MCHID}&nonce_str={$noncestr}&notify_url={$notifyUrl}&openid=".cookie("openid")."&out_trade_no={$orderid}&spbill_create_ip={$_SERVER['REMOTE_ADDR']}&total_fee={$price}&trade_type=JSAPI";
    $stringSignTemp=$stringA."&key=".C('KEY'); //注：key为商户平台设置的密钥key
    $sign=strtoupper(md5($stringSignTemp));

    $strData=array(
        'appid'=>$APPID,
        'mch_id'=>$MCHID,
        'nonce_str'=>$noncestr,
        'sign'=>$sign,
        'body'=>$body,
        'out_trade_no'=>$orderid,
        'total_fee'=>$price,
        'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'],
        'notify_url'=>$notifyUrl,
        'trade_type'=>'JSAPI',
        'openid'=>cookie("openid"),
    );

    $xml = "<xml>";
    foreach ($strData as $key=>$val)//数组转xml
    {
        if (is_numeric($val)){
            $xml.="<".$key.">".$val."</".$key.">";
        }else{
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
    }
    $xml.="</xml>";
    $strData=$xml;
    //$json=json_encode($data,JSON_UNESCAPED_UNICODE);
    $headers=array(
        'Content-Type:text/xml;charset=utf-8',
    );
    $url="https://api.mch.weixin.qq.com/pay/unifiedorder";

    $ch = curl_init();
    curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
    curl_setopt($ch,CURLOPT_URL,$url); //设置请求地址
    curl_setopt($ch,CURLOPT_POST,true); //post请求
    curl_setopt($ch,CURLOPT_POSTFIELDS,$strData);// post请求的数据
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不需要证书验证
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//不直接输出到页面
    $json = curl_exec($ch);
    return $json;
    curl_close($ch);
}

function H5ZMwxzhifu($nick,$name,$orderid,$csName){//知命H5微信支付
    $csChannel=cookie('channel');

    if($csChannel=='test'){//测试

    }else{
        $jumpUrl=cookie($orderid.'jumpUrl');
        if($jumpUrl){header("location:".$jumpUrl);exit;}
    }

    $price=cookie('price');
    if(empty($nick)){echo 'nike';exit;}
    $arrdata[0]=S('sm_h5test|'.$orderid);



    if($nick=='BZJPPT'){//结果二次支付
        $price=cookie('pricePt');
    }elseif($arrdata[0]['price']>0&&$arrdata[0]['status']!=1){
        if(cookie('wxzfNum')){
            cacheZhiFuOrderidDelete($orderid);//删除用户我的测试订单
            $orderid=$nick.date('Ymd').mt_rand(10000,99999).'c'.date('His');//重新生成订单
            cookie('orderid',$orderid);
            $arrdata[0]['ordernum']=$orderid;
            S('sm_h5test|'.$orderid,$arrdata[0],592000);//2592000为30天
            cacheZhiFuOrderid($orderid);//支付页缓存订单操作
            //M()->query("insert into sm_h5test(ordernum,price,username,typeid,sex,status,datetype,year,month,day,hour,minute,channel,ip,appuserid,auto_send_sms) select '{$orderid}' as ordernum,price,username,typeid,sex,status,datetype,year,month,day,hour,minute,channel,ip,appuserid,auto_send_sms from sm_h5test where id='{$arrdata[0]['id']}'");
            if($nick=='HH'||$nick=='HY'){
                //M()->query("insert into sm_h5test(ordernum,price,username,typeid,sex,status,datetype,year,month,day,hour,channel,ip,appuserid) select '{$orderid}_' as ordernum,price,username,typeid,sex,status,datetype,year,month,day,hour,channel,ip,appuserid from sm_h5test where id={$arrdata[0]['id']}+1");
            }
        }
        cookie('wxzfNum',1);
    }else{
        header('location:'.U('Index/mycesuan','',false));
        exit;
    }



    wxOrderPayjudge($orderid);//微信支付订单判断

    $price*=100;

    if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {$ip = getenv('HTTP_CLIENT_IP');
    } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {$ip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {$ip = getenv('REMOTE_ADDR');
    } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {$ip = $_SERVER['REMOTE_ADDR'];
    }
   $ip=preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';


    $scene_info="{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"https://hy.yixueqm.com\",\"wap_name\": \"知命支付\"}}";

    $channel=cookie('channel');
    $noncestr=noncestr(15);
    $KEY=C('KEY');
    $host=$_SERVER['HTTP_HOST'];
    if($channel=='C001'){
        $MCHID=C('C001GMCHID');
        $APPID=C('C001APPID');
    }elseif($_SERVER['HTTP_HOST']=='wx.zhimingds.com'){
        $MCHID=C('XzGMCHID');
        $APPID=C('XzAPPID');
        $KEY=C('XzKey');
    }elseif($csChannel=='baidu_mw'||$csChannel=='lz_wnl'||$host=='m.baobaoquming.com.cn'){
        $MCHID=C('GMCHID');
        $APPID=C('APPID');//知命
    } else{
        $MCHID=C('H5GMCHID');
        $APPID=C('H5APPID');//趣测
        //$MCHID=C('GMCHID');
        //$APPID=C('APPID');//知命
    }

    //重新定义商品名称
    $name="订单号:{$orderid},客服微信号:qumingxiaoxue";

    $body=$name;
    $type='MWEB';
    $notifyUrl="http://{$_SERVER['HTTP_HOST']}/zhiming/index.php/Home-Index-notify_urlwx";
    $stringA="appid=".$APPID."&body={$body}&mch_id={$MCHID}&nonce_str={$noncestr}&notify_url={$notifyUrl}&out_trade_no={$orderid}&scene_info={$scene_info}&spbill_create_ip={$ip}&total_fee={$price}&trade_type={$type}";
    $stringSignTemp=$stringA."&key=".$KEY; //注：key为商户平台设置的密钥key
    $sign=strtoupper(md5($stringSignTemp));

    $strData=array(
        'appid'=>$APPID,
        'mch_id'=>$MCHID,
        'nonce_str'=>$noncestr,
        'sign'=>$sign,
        'body'=>$body,
        'out_trade_no'=>$orderid,
        'total_fee'=>$price,
        'spbill_create_ip'=>$ip,
        'notify_url'=>$notifyUrl,
        'trade_type'=>$type,
        'scene_info'=>$scene_info,
    );
    $staDataArr=$strData;


    $xml = "<xml>";
    foreach ($strData as $key=>$val)//数组转xml
    {
        if (is_numeric($val)){
            $xml.="<".$key.">".$val."</".$key.">";
        }else{
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
    }
    $xml.="</xml>";
    $strData=$xml;
    //$json=json_encode($data,JSON_UNESCAPED_UNICODE);
    $headers=array(
        'Content-Type:text/xml;charset=utf-8',
    );
    $url="https://api.mch.weixin.qq.com/pay/unifiedorder";

    $ch = curl_init();
    curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
    curl_setopt($ch,CURLOPT_URL,$url); //设置请求地址
    curl_setopt($ch,CURLOPT_POST,true); //post请求
    curl_setopt($ch,CURLOPT_POSTFIELDS,$strData);// post请求的数据
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不需要证书验证
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//不直接输出到页面
    $json = curl_exec($ch);
    $code = curl_getinfo($ch,CURLINFO_HTTP_CODE);

    $xmlstring = simplexml_load_string($json, 'SimpleXMLElement', LIBXML_NOCDATA);
    $val = json_decode(json_encode($xmlstring),true);
    curl_close($ch);


    $zfUrl=cookie('zfUrl');$redirect_url=$zfUrl;
    if(empty($zfUrl)){
        $redirect_url='http://'.$_SERVER['HTTP_HOST']."/zhiming/index.php/Home-Index-return_urlwx?orderid={$orderid}&csName={$csName}";
    }

    $redirect_url=urlencode($redirect_url);

    if(empty($val['mweb_url'])){
        if(mb_substr($val['err_code_des'],0,3)==201){
            $wzurl=wxJsdkData();
            echo $val['err_code_des'];
            redirect($wzurl);
        }
        dump($staDataArr);
        dump($val);echo 'H5ZMwxzhifu';exit;
    }

    if($csChannel=='qudao100'){
        $jumpUrl=$val['mweb_url'];
    }else{
        $jumpUrl=$val['mweb_url']."&redirect_url=".$redirect_url;
    }


    if(cookie('channel')=='qudao146'){
        cookie('mweb_url',$jumpUrl);
        redirect(U('Index/paywxJump','',false));exit;
    }
    if($val['mweb_url']){
        cookie($orderid.'jumpUrl',$jumpUrl,250);
    }

    header("location:".$jumpUrl);
}
function wxsaoma($nick,$name,$orderid){//微信扫码下单
    if(empty($nick)){echo 'nike';exit;}

    $price=cookie('price');
    $price*=100;

    $noncestr=noncestr(15);

    $MCHID=C('H5GMCHID');
    $APPID=C('H5APPID');

    $body=$name;
    $notifyUrl="http://{$_SERVER['HTTP_HOST']}/zhiming/index.php/Home-Index-notify_urlwx";
    $stringA="appid=".$APPID."&body={$body}&mch_id={$MCHID}&nonce_str={$noncestr}&notify_url={$notifyUrl}&out_trade_no=".$orderid."&spbill_create_ip={$_SERVER['REMOTE_ADDR']}&total_fee={$price}&trade_type=NATIVE";
    $stringSignTemp=$stringA."&key=".C('KEY'); //注：key为商户平台设置的密钥key
    $sign=strtoupper(md5($stringSignTemp));

    $strData=array(
        'appid'=>$APPID,
        'mch_id'=>$MCHID,
        'nonce_str'=>$noncestr,
        'sign'=>$sign,
        'body'=>$body,
        'out_trade_no'=>$orderid,
        'total_fee'=>$price,
        'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'],
        'notify_url'=>$notifyUrl,
        'trade_type'=>'NATIVE',
    );

    $xml = "<xml>";
    foreach ($strData as $key=>$val)//数组转xml
    {
        if (is_numeric($val)){
            $xml.="<".$key.">".$val."</".$key.">";
        }else{
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
    }
    $xml.="</xml>";
    $strData=$xml;
    //$json=json_encode($data,JSON_UNESCAPED_UNICODE);
    $headers=array(
        'Content-Type:text/xml;charset=utf-8',
    );

    $saomaUrl=cookie('saoma'.$orderid);
    if($saomaUrl){
        return $saomaUrl;
    }else{
        $url="https://api.mch.weixin.qq.com/pay/unifiedorder";
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
        curl_setopt($ch,CURLOPT_URL,$url); //设置请求地址
        curl_setopt($ch,CURLOPT_POST,true); //post请求
        curl_setopt($ch,CURLOPT_POSTFIELDS,$strData);// post请求的数据
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不需要证书验证
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//不直接输出到页面
        $json = curl_exec($ch);
        $valuesArr = json_decode(json_encode(simplexml_load_string($json, 'SimpleXMLElement', LIBXML_NOCDATA)), true);//把xml字符串解析成数组
        cookie('saoma'.$orderid,$valuesArr['code_url'],300);
        return $valuesArr['code_url'];
        curl_close($ch);
    }
}

//function lianshangZF($csName,$orderid){//连尚支付
//    $openId=cookie('uid');	  //String(32)连尚商户在商品平台ID(若没有建议传用户唯一id)
//    $merchantNo=11568186;  //盛付通分配的商户号
//    $merchantOrderNo=$orderid;	  //商户系统内部的订单号，32个字符，可包含字母、数字组成
//    $orderAmount=cookie('price');	  //订单总金额，单位为元，最多支持小数点两位
//    $goodsName=$csName;	  //商品名称
//    $appName="八字精批";  //连尚平台审核通过的应用名
//    $appId="TD0208"; //连尚平台审核通过的应用id
//    $notifyUrl="https://hy.yixueqm.com/zhiming/index.php/Home-Index-lianshang_return_urlYB";	//接收支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。
//    $strYC=$openId."&".$merchantNo."&".$merchantOrderNo."&".$orderAmount."&".$notifyUrl."&".$goodsName."&".$appId."&".$appName;
//    //$RSA=RSA($strYC);
//    //$sign=$RSA;   //对参数进行加签的结果，RSA签名见附录(sign字段需要做urlencode)
//    //dump($sign);
//    $dataArr=array(
//        "openId"=>$openId,
//        "merchantNo"=>$merchantNo,
//        "merchantOrderNo"=>$merchantOrderNo,
//        "orderAmount"=>$orderAmount,
//        "goodsName"=>$goodsName,
//        "appName"=>$appName,
//        "appId"=>$appId,
//        "notifyUrl"=>$notifyUrl
//    );
//    //dump($dataArr);exit;
//
//    $json=json_encode($dataArr,JSON_UNESCAPED_UNICODE);
//    //$url="http://sm.ddznzj.com/sm/pay/wifipay?openId={$openId}&merchantNo={$merchantNo}&merchantOrderNo={$merchantOrderNo}&orderAmount={$orderAmount}&goodsName={$goodsName}&appName={$appName}&appId={$appId}&notifyUrl={$notifyUrl}";
//    //$url="http://sm.ddznzj.com/sm/dynamics/list?page=0";
//    $url="http://sm.ddznzj.com/sm/pay/wifipay";
//    $headers=array(
//        'Content-Type:application/json;charset=utf-8',
//    );
//    $ch = curl_init();
//    curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
//    curl_setopt($ch,CURLOPT_URL,$url); //设置请求地址
//    curl_setopt($ch,CURLOPT_POST,true); //post请求
//    curl_setopt($ch,CURLOPT_POSTFIELDS,$json);// post请求的数据
//    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不需要证书验证
//    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
//    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//不直接输出到页面
//    $json = curl_exec($ch);
//
//    $sign=$json;
//    $dataArr=array(
//        "openId"=>$openId,
//        "merchantNo"=>$merchantNo,
//        "merchantOrderNo"=>$merchantOrderNo,
//        "orderAmount"=>$orderAmount,
//        "goodsName"=>$goodsName,
//        "appName"=>$appName,
//        "appId"=>$appId,
//        "notifyUrl"=>$notifyUrl,
//        "sign"=>$sign,
//    );
//    $json=json_encode($dataArr,JSON_UNESCAPED_UNICODE);
//    //dump($json);exit;
//    curl_close($ch);
//    $url="https://hy.yixueqm.com".U("Index/lianshang_return_url",'',false);
//    header("location:http://ebinfonew.shengpay.com/Activity/wifi/rw/money/zhifu/pay.html?ext={$json}&url={$url}");
//}

function curlGet($url){
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url); //设置请求地址
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不需要证书验证
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//不直接输出到页面
    $json = curl_exec($ch);
    curl_close($ch);
    return $json;
}
function curlPost($url,$strData){
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url); //设置请求地址
    curl_setopt($ch,CURLOPT_POST,true); //post请求
    curl_setopt($ch,CURLOPT_POSTFIELDS,$strData);// post请求的数据
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不需要证书验证
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//不直接输出到页面
    $json = curl_exec($ch);
    curl_close($ch);
    return $json;
}

function wechatEmpower(){//域名微信授权跳转
    $user_agent = $_SERVER['HTTP_USER_AGENT'];//用户使用的浏览器，操作系统等信息。
    if (strpos($user_agent, 'MicroMessenger') == false) {
        //非微信浏览器访问
    }else{
        getToken();
        getTicket();
        $wzurl=wxJsdkData();
        if(!empty($_REQUEST['code'])){
            cookie('code',$_REQUEST['code'],7100);
        }
        getCode($wzurl);
        getOopenid();
        cookie('code',null);
        $openid=cookie('openid');
        $url=cookie('http').'://wx1.bazijingpi.top'.$_SERVER['REQUEST_URI']."&openid={$openid}";
        redirect($url);
        exit;
    }
}

